<template>
  <div class="certificates-page">
    <div class="page-header">
      <h2>我的证书</h2>
      <div class="filter-box">
        <el-input v-model="searchQuery" placeholder="搜索证书" clearable style="width: 220px">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="resetSearch">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </div>
    </div>

    <div class="certificates-container" v-loading="loading">
      <template v-if="certificates && certificates.length > 0">
        <el-table :data="certificates" style="width: 100%" border>
          <el-table-column prop="examName" label="考试名称" min-width="120" />
          <el-table-column prop="issueDate" label="颁发日期" min-width="160" />
          <el-table-column prop="certificateCode" label="证书编号" min-width="200" />
          <el-table-column prop="issuer" label="颁发单位" min-width="100" />
          <el-table-column prop="status" label="状态" min-width="80" />
          <el-table-column label="操作" min-width="140">
            <template #default="scope">
              <el-button type="success" size="small" @click="downloadCertificate(scope.row)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[8, 16, 24, 32]"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes, prev, pager, next, jumper"
            background
          />
        </div>
      </template>
      <el-empty v-else description="暂无证书记录" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Calendar, Document } from '@element-plus/icons-vue'
import { getStudentCertificates } from '@/api/certificate'
import { useUser } from '@/stores/userInfo'

const userStore = useUser()
const loading = ref(false)
const certificates = ref([]) // 确保初始化为一个空数组
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)
const searchQuery = ref('')

// 获取证书列表
const fetchCertificates = async () => {
  loading.value = true
  try {
    const schoolNumber = userStore.userInfo?.schoolNumber
    if (!schoolNumber) {
      ElMessage.error('未获取到用户信息')
      return
    }
    
    const params = {
      studentId: schoolNumber,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchQuery.value
    }
    
    const res = await getStudentCertificates(params)
    
    if (res.code === 200) {
      certificates.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取证书列表失败')
    }
  } catch (error) {
    ElMessage.error('获取证书列表失败')
    console.error('证书接口错误:', error)
  } finally {
    loading.value = false
  }
}

// 下载证书
const downloadCertificate = (certificate) => {
  const link = document.createElement('a')
  link.href = certificate.pdfUrl
  link.download = `证书-${certificate.certificateCode}.pdf`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchCertificates()
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = ''
  currentPage.value = 1
  fetchCertificates()
}

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchCertificates()
}

// 处理每页数量改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchCertificates()
}

// 页面加载时获取数据
onMounted(() => {
  fetchCertificates()
})
</script>

<style lang="scss" scoped>
.certificates-page {
  padding: 20px;
  background-color: #f6f8fa;
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 10px 0;
    border-bottom: 1px solid #e4e7ed;

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
      font-weight: bold;
    }

    .filter-box {
      display: flex;
      gap: 10px;
      align-items: center;
    }
  }

  .certificates-container {
    margin-top: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>